﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Threading;
using System.Reflection;

namespace AccessFormProperty
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "..\\..\\..\\AppTest\\bin\\debug\\AppTest.exe";
            string formname = "AppTest.Form1";


            Prompot("Launch app...");
            Form f = LaunchApp(filename, formname);

            DGetFormPropertyValue d = new DGetFormPropertyValue(GetFormPropertyValue);
            object[] o = new object[] { f,"Location"};

            Prompot("get location...");
            System.Drawing.Point p = (System.Drawing.Point)f.Invoke(d, o);
            Console.WriteLine("Location, x:{0},y:{1}",p.X,p.Y);

            Console.ReadLine();

        }

        private static  void Prompot(string display)
        {
            Console.WriteLine(display);
            Console.ReadLine();
        }

        private static object GetFormPropertyValue(Form f, string propertyname)
        {
            Type t = f.GetType();
            PropertyInfo pi = t.GetProperty(propertyname);
            return pi.GetValue(f);
        }
        private delegate object DGetFormPropertyValue(Form f, string propertyname);
       

        private static Form LaunchApp(string filename, string formname)
        {
            Assembly assembly = Assembly.LoadFrom(filename);
            Type t = assembly.GetType(formname);

            Form f = (Form) assembly.CreateInstance(t.FullName);


            AppState aps = new AppState (f);
            ThreadStart ts = new ThreadStart (aps.AppRun);
            Thread thread = new Thread(ts);
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();


            return f;
        }
    }

    class AppState
    {
        private Form form;
        public AppState(Form f)
        {
            form = f;
        }

        public void AppRun()
        {
            Application.Run(form);
        }
    }
}
